<?php
//by willson 105328468@qq.com 2014/10/11
//index page interface

class order_model extends base_model {
	private $commission_mod;

	public function __construct() {
		parent::__construct();
		$this->commission_mod = m("commission");
	}

	//获取详情
	public function detail($id) {
		$sql = "SELECT * FROM {$this->tbp}order WHERE id='{$id}'";
		$row = $this->db->get_row($sql);
		return $row;
	}

	// 0：未支付，1：已支付，2：已发货，3：完成（已收货），-1：取消，-2：退款，-3：退货，-4：未确认
	public function status_name($status) {
		$str = $status;
		switch ($status) {
			case 0:$str = '未支付';break;
			case 1:$str = '已支付';break;
			case 2:$str = '已完成';break;
			case -1:$str = '已取消';break;
		}
		return $str;
	}

	//获取折扣

	//确认收货
	public function shouhuo($order_id=0, $member_id=0) {
		if (!$order_id) $order_id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		if ($order_id<=0) error('信息错误');
		if ($member_id==0) $member_id = $this->member_id;
		$sql = "SELECT * FROM {$this->tbp}order WHERE id='{$order_id}' AND member_id='{$member_id}'";
		$order = $this->db->get_row($sql);
		if (!$order) error("找不到此订单id: {$order_id}");
		//已经确认过收货的，不能再确认。
		if ($order->status>=3) return;
		$sql = "UPDATE {$this->tbp}order SET status='3', shouhuo_time='".time()."' WHERE id='{$order_id}' AND member_id='{$member_id}'";
		$rs = $this->db->query($sql);
		//订单佣金转账到会员的佣金
		if ($rs) {
			$this->commission_mod->turn_commission($order_id);
		}
		//success('ok');
	}

	//是否阅读订单
	public function readed($order) {
		$readed = 0;
		if ($this->member_id){
			if ($_SESSION['member']->member_type==2) {
				if ($order->reseller_read_time>0) $readed = 1;
			} else if ($_SESSION['member']->member_type==3) {
				if ($order->factory_read_time>0) $readed = 1;
			}
		}
		return $readed;
	}

	public function pay_method($method) {
		if ($method=='alipay') {
			$method = "支付宝支付";
		} else if ($method=='wxpay') {
			$method = "APP内微信支付";
		} else if ($method=='wxpay_h5') {
			$method = "服务号内支付";
		} else if ($method=='yue') {
			$method = "余额支付";
		}
		return $method;
	}

	//支付成功后，设置订单状态，更新信息
	public function handle_paid_order($out_trade_no, $check_order_status=true) {
		if ($out_trade_no) {
			$flag = substr($out_trade_no, 0, 2);
			if ($flag == "TC") {
				$sql = "SELECT * FROM {$this->tbp}member_meal WHERE order_sn='{$out_trade_no}' AND status='0'";
				$meal = $this->db->get_row($sql);
				$this->log_result($sql);
				if ($meal) {
					$sql = "UPDATE {$this->tbp}member_meal SET status='1', pay_time='".time()."' WHERE order_sn='{$out_trade_no}' AND status='0'";
					$this->db->query($sql);
					$this->log_result($sql);
					//支付成功后写入套餐历史
					$sql = "INSERT INTO {$this->tbp}meal_history(meal_id, member_id, add_time, order_id, title, project_id, type)
						VALUES('{$meal->meal_id}', '{$meal->member_id}', '".time()."', '{$meal->id}', '购买套餐', '0', '1')";
					$this->db->query($sql);
					$this->log_result($sql);
				}
				//$sql = "UPDATE {$this->tbp}member_meal SET status='1', pay_time='".time()."' WHERE order_sn='{$out_trade_no}' AND status='0'";
				//echo $sql;
				//$this->db->query($sql);
				//$this->log_result($sql);
				//logResult($sql);
			} else if ($flag == "CZ") {
				$sql = "SELECT recharged_money, member_id FROM {$this->tbp}member_recharge WHERE order_sn='{$out_trade_no}' AND status='0'";
				$row = $this->db->get_row($sql);
				if ($row) {
					$sql = "UPDATE {$this->tbp}member_recharge SET status='1', pay_time='".time()."' WHERE order_sn='{$out_trade_no}'";
					$this->db->query($sql);
					$sql = "UPDATE {$this->tbp}member SET `money`=`money`+{$row->recharged_money} WHERE id='{$row->member_id}'";
					$this->db->query($sql);
				}
				$this->log_result($sql);
				//logResult($sql);
			} else {
				//订购服务的订单
				//check_order_status，是否检查订单的状态，如果支付宝回调，必须检查；在下单时，则不需要
				if ($check_order_status) {
					$status_sql = " AND status='0'";
				} else {
					$status_sql = "";
				}
				$sql = "SELECT id, member_id, status FROM {$this->tbp}order WHERE order_sn='{$out_trade_no}' {$status_sql}";
				$order = $this->db->get_row($sql);
				if ($order) {
				//if ($order) {
					$sql = "UPDATE {$this->tbp}order SET status='1', pay_time='".time()."' WHERE id='{$order->id}'";
					$this->db->query($sql);
					$this->log_result("{$out_trade_no}->{$order->id}: {$sql}");
					//减少套餐使用
					$meal_mod = m("meal");
					$meal_mod->consume($order->id);
				} else {
					$this->log_result("{$out_trade_no}不存在");
				}
				//logResult($sql);
			}
		}
	}

	//取消订单时退还金额
	public function return_yue_and_commission($order_id) {
		$sql = "SELECT o.*, m.money as member_money, m.commission as member_commission FROM {$this->tbp}order o INNER JOIN {$this->tbp}member m ON o.member_id=m.id
			WHERE o.id='{$order_id}' AND member_id='{$this->member_id}'";
		$order = $this->db->get_row($sql);
		if ($order && $order->pay_method=='yue' && $order->status>0 && intval($order->cancel_time)==0) {
			//退还佣金和余额
			$commission = floatval($order->member_commission + $order->used_commission);
			$money = floatval($order->member_money + $order->used_money);
			$sql = "UPDATE {$this->tbp}member SET commission='{$commission}', money='{$money}' WHERE id='{$this->member_id}'";
			//echo $sql;
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order SET cancel_time='".time()."' WHERE id='{$order_id}'";
			$this->db->query($sql);
			$_SESSION['member']->commission = $commission;
			$_SESSION['member']->money = $money;
		}
	}

	//写入日志
	private function log_result($log) {
		$file = fopen("temp/pay.log","a+");
		fwrite($file, date("Y-m-d H:i:s") ." {$log} \n\r<hr> ");
		fclose($file);
	}

}
